package com.test.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: junwe
 * @Date: 2020/12/15 21:48
 */
public class ProxyFactory {

    /**
     * 目标对象
     */
    private Object target;

    /**
     * 对目标对象初始化
     * @param target
     */
    public ProxyFactory(Object target) {
        this.target = target;
    }

    /**
     * 给目标对象生成一个代理对象
     * @return
     */
    public Object getProxyTarget() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("开始JDK代理");
                // 反射机制调用目标对象方法
                Object invoke = method.invoke(target, args);
                System.out.println("结束JDK代理");
                return invoke;
            }
        });
    }
}
